package priv.conceit.study.book.lambda.chapter5;


import priv.conceit.study.book.lambda.common.entity.Album;
import priv.conceit.study.book.lambda.common.entity.Artist;
import priv.conceit.study.book.lambda.common.entity.SampleData;
import priv.conceit.study.book.lambda.common.entity.Track;

import java.util.Comparator;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;



/**
 * 高级集合类 和 收集器
 * 5.3.2
 * 转换为值
 *
 *
 *
 * @author Conceit
 * @since 1.0.0, 2021/9/28
 */
public class ToValues {

    public static void main(String[] args) {
        //使用收集器生成一个值

        Stream<Album> albumStream=SampleData.albumAllStream;
        //findTrackCountMin(albumStream);
        findTrackAvg(albumStream);

    }

    //查询歌曲最多的专辑
    //直接统计列表数据，中间中间操作比如 filter map 是对单个元素进行操作。有区别
    public static void findTrackCountMin(Stream<Album> albumStream){
        //Function<Album,Long> albumLongFunction=album->album.getTracks().count();
        Optional<Album> albumOptional=albumStream.collect(Collectors.minBy(Comparator.comparing(album->album.getTracks().count())));
        if(albumOptional.isPresent()){
            System.out.println(albumOptional.get().getName());
        }
    }

    //查询歌曲平均数
    public static void findTrackAvg(Stream<Album> albumStream){
        double  avg=albumStream.collect(Collectors.averagingLong(album -> album.getTracks().count()));
        System.out.println(avg);
    }
}
